import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {
  View, Image, Text, TextInput, TouchableOpacity, StyleSheet
} from 'react-native'

export const InputTypes = {
  PHONE: 'phone',
  PASSWORD: 'password'
}

export default class NameInput extends Component {
  static propTypes = {
    text: PropTypes.string,
    value: PropTypes.string,
    maxValue: PropTypes.string,
    inputType: PropTypes.string,
    autoFocus: PropTypes.bool,
    multiline: PropTypes.bool,
    maxLength: PropTypes.number,
    containerStyle: PropTypes.any,
    inputStyle: PropTypes.any,
    imageStyle: PropTypes.any,
    showLeftText: PropTypes.bool,
    leftText: PropTypes.string,
    leftTextStyle: PropTypes.any,
    showRightText: PropTypes.bool,
    rightText: PropTypes.string,
    rightTextStyle: PropTypes.any,
    showRightImage: PropTypes.bool,
    rightImage: PropTypes.any,
    rightImageStyle: PropTypes.any,
    rightImageEvent: PropTypes.func,
    showRightView: PropTypes.bool,
    isUseLabelPlaceholder: PropTypes.bool,
    rightView: PropTypes.any,
    clearImage: PropTypes.any,
    editable: PropTypes.any,
    hideClearImage: PropTypes.bool,
    placeholder: PropTypes.string,
    placeholderTextColor: PropTypes.string,
    onPress: PropTypes.func,
    getTarget: PropTypes.func,
    callback: PropTypes.func
  }

  constructor (props) {
    super(props)
    this.mounted = false
    this.state = {
      value: props.text || '',
      showPassword: false
    }
  }

  componentDidMount () {
    this.mounted = true
  }

  componentWillReceiveProps (nextProps) {
    this.setState({ value: nextProps.text })
  }

  componentWillUnmount () {
    this.mounted = false
  }

  render () {
    let { value, showPassword } = this.state
    let { placeholderTextColor, inputType = 'common', editable } = this.props
    return (
      <TouchableOpacity
        style={[styles.container, this.props.containerStyle]}
        onPress={this.props.onPress || null}
        activeOpacity={this.props.onPress ? 0.4 : 1}>
        {this.renderLeftText()}
        {
          editable === false
          ? <View
            ref={this.refTextInput}
            style={[styles.textInput, this.props.inputStyle]}
            underlineColorAndroid={'transparent'}
            secureTextEntry={this.isPasswordType(inputType)
              ? !showPassword : false}
            onChangeText={this.handleChangeValue}
            onLayout={this.handleGetTarget}
            returnKeyType='search'
            returnKeyLabel={'搜索'}
            placeholderTextColor={placeholderTextColor || '#8e8e93'}
            {...this.props}>
              <Text style={{
                color: this.props.isUseLabelPlaceholder ? '#8e8e93' : 'black'
              }} numberOfLines={1}>{value}</Text>
            </View>
          : <TextInput
            ref={this.refTextInput}
            style={[styles.textInput, this.props.inputStyle]}
            underlineColorAndroid={'transparent'}
            secureTextEntry={this.isPasswordType(inputType)
              ? !showPassword : false}
            onChangeText={this.handleChangeValue}
            onLayout={this.handleGetTarget}
            value={value}
            returnKeyType='search'
            returnKeyLabel={'搜索'}
            placeholderTextColor={placeholderTextColor || '#8e8e93'}
            {...this.props}
          />
        }
        {this.renderClearView()}
        {this.renderRightText()}
        {this.renderRightImage()}
        {this.renderRightView()}
      </TouchableOpacity>
    )
  }

  renderLeftText = () => {
    let { showLeftText, leftText, leftTextStyle } = this.props
    if (showLeftText && leftText) {
      return (
        <Text style={[styles.leftText, leftTextStyle]}>
          {leftText}
        </Text>
      )
    }
    return null
  }

  renderRightView = () => {
    let { showRightView, rightView } = this.props
    if (showRightView && rightView) {
      if (typeof rightView === 'function') {
        return rightView()
      } else if (typeof rightView === 'object') {
        return rightView
      }
      return null
    }
  }

  renderRightText = () => {
    let { showRightText, rightText, rightTextStyle } = this.props
    if (showRightText && rightText) {
      return (
        <Text style={[styles.rightText, rightTextStyle]}>
          {rightText}
        </Text>
      )
    }
    return null
  }

  renderRightImage = () => {
    let { showRightImage, rightImage } = this.props
    if (showRightImage && rightImage) {
      return (
        <TouchableOpacity
          style={[styles.imageContainer, this.props.rightImageStyle]}
          onPress={this.props.rightImageEvent}
          onLayout={this.handleGetTarget}>
          <Image
            style={styles.image}
            onLayout={this.handleGetTarget}
            source={rightImage} />
        </TouchableOpacity>
      )
    }
    return null
  }

  renderClearView = () => {
    let { value } = this.state
    let { hideClearImage } = this.props
    if (value && value.length > 0 && !hideClearImage) {
      return (
        <TouchableOpacity
          style={[styles.imageContainer, this.props.imageStyle]}
          onPress={this.handleClearValue}
          onLayout={this.handleGetTarget}>
          <Image
            style={styles.image}
            onLayout={this.handleGetTarget}
            source={this.props.clearImage ||
              require('src/assets/close.png')} />
        </TouchableOpacity>
      )
    } else if (!hideClearImage) {
      return (
        <View
          style={[styles.imageContainer, this.props.imageStyle]}
          onPress={this.handleClearValue}
          onLayout={this.handleGetTarget} />
      )
    } else {
      return null
    }
  }

  refTextInput = (ref) => { this.textInput = ref }

  isPasswordType = (type) => {
    return type === InputTypes.PASSWORD
  }

  handleToggleShowPassword = () => {
    this.setState({ showPassword: !this.state.showPassword })
  }

  handleGetTarget = (event) => {
    if (this.props.getTarget) {
      this.props.getTarget(event)
    }
  }

  handleChangeValue = (value) => {
    let { inputType, maxValue, callback } = this.props
    if (inputType === InputTypes.PHONE) {
      value = value.replace(/[^\d]/g, '')
    } else if (inputType === InputTypes.MONEY) {
      value = value.replace(/^\D*([0-9]\d*\.?\d{0,6})?.*$/, '$1')
      if (value && maxValue) {
        if (parseFloat(value) > parseFloat(maxValue)) {
          value = maxValue
        }
      }
    } else if (inputType === InputTypes.COUNT) {
      value = value.replace(/^\D*([0-9]\d*\.?\d{0,6})?.*$/, '$1')
      if (value && maxValue) {
        if (parseFloat(value) > parseFloat(maxValue)) {
          value = maxValue
        }
      }
    }
    this.mounted && this.setState({ value: value })
    callback && callback(value)
  }

  handleClearValue = () => {
    this.handleChangeValue('')
  }
}

const styles = StyleSheet.create({
  container: {
    height: 50,
    backgroundColor: 'transparent',
    flexDirection: 'row',
    alignItems: 'center'
  },
  textInput: {
    flex: 1,
    paddingLeft: 16,
    paddingRight: 16,
    fontSize: 14,
    color: '#2e2e2e'
  },
  imageContainer: {
    width: 45,
    paddingRight: 14,
    justifyContent: 'center',
    alignItems: 'flex-end'
  },
  leftText: {
    fontSize: 15,
    color: '#2e2e2e'
  },
  image: {
    resizeMode: 'contain'
  },
  errorText: {
    fontSize: 12,
    color: 'red'
  }
})
